from kubernetes import client, config

config.load_kube_config(config_file='/tmp/config')

v1 = client.CoreV1Api()
api_instance = client.CoreV1Api()

namespace = 'my-test'

# 创建 Pod
pod_manifest = {
    'apiVersion': 'v1',
    'kind': 'Pod',
    'metadata': {
        'name': 'mypod'
    },
    'spec': {
        'containers': [{
            'name': 'mycontainer',
            'image': 'nginx:latest',
            'ports': [{
                'containerPort': 80,
                'hostPort': 80
            }]
        }]
    }
}
resp = v1.create_namespaced_pod(body=pod_manifest, namespace=namespace)
print("Pod created. status='%s'" % resp.status.phase)

# 创建 Service
service_manifest = {
    'apiVersion': 'v1',
    'kind': 'Service',
    'metadata': {
        'name': 'myservice'
    },
    'spec': {
        'selector': {
            'app': 'myapp'
        },
        'ports': [{
            'protocol': 'TCP',
            'port': 80,
            'targetPort': 80,
            'nodePort': 30001
        }],
        'type': 'NodePort'
    }
}
resp = api_instance.create_namespaced_service(
    body=service_manifest,
    namespace=namespace)
print("Service created. status='%s'" % resp)
